package com.ui.zhong.webview.webviewproc

import android.content.Context
import android.util.AttributeSet
import android.webkit.WebView
import android.util.Log
import android.webkit.JavascriptInterface
import com.google.gson.Gson
import com.ui.zhong.webview.WebViewCallback
import com.ui.zhong.webview.bean.JsParam
import com.ui.zhong.webview.webviewproc.chromeclient.CustomWebChromeClient
import com.ui.zhong.webview.webviewproc.settings.WebViewDefaultSettings
import com.ui.zhong.webview.webviewproc.webviewclient.CustomWebViewClient


class ComposeWebView : WebView {
    private val TAG = "ComposeWebView"

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    init {
        WebViewProcCmdDispatcher.getInstance().initAIDLConnection()
        WebViewDefaultSettings.getInstance().setSettings(this)
        // 会注入到window中
        // 会注入到window中
        addJavascriptInterface(this, "ComposeWebView")
    }

    fun registerWebViewCallBack(callBack: WebViewCallback?) {
        webViewClient = CustomWebViewClient(callBack)
        webChromeClient = CustomWebChromeClient(callBack)
    }


    @JavascriptInterface
    fun takeNativeAction(jsParam: String) {
        Log.i(TAG, jsParam)
        val jsonObject = Gson().fromJson(jsParam, JsParam::class.java)
        jsonObject?.run {
            WebViewProcCmdDispatcher.getInstance().executeCommand(
                jsonObject.name,
                Gson().toJson(jsonObject.param),this@ComposeWebView
            )
        }
    }


    fun handleCallBack(callbackname: String?, response: String?) {
        callbackname?.run {
            response?.run {
                post {
                    val jscode = "javascript:xiangxuejs.callback('$callbackname',$response)"
                    Log.e("xxxxxx", jscode)
                    evaluateJavascript(jscode, null)
                }
            }
        }
    }
}